/**
 * 密码管理器UI交互模块
 * 负责用户界面的显示和交互逻辑
 */
const UIModule = {
    // DOM元素缓存
    elements: {},
    // 自动登出计时器
    autoLogoutTimer: null,
    // 当前编辑的密码ID
    currentEditingId: null,

    /**
     * 初始化UI
     */
    init() {
        this.cacheElements();
        this.bindEvents();
        this.checkInitialState();
        this.initEventListeners();
    },

    /**
     * 缓存常用DOM元素
     */
    cacheElements() {
        // 登录相关
        this.elements.loginContainer = document.getElementById('login-container');
        this.elements.loginForm = document.getElementById('login-form');
        this.elements.masterPassword = document.getElementById('master-password');
        
        // 主应用容器
        this.elements.appContainer = document.getElementById('app-container');
        
        // 导航相关
        this.elements.navPasswords = document.getElementById('nav-passwords');
        this.elements.navGenerator = document.getElementById('nav-generator');
        this.elements.navSettings = document.getElementById('nav-settings');
        this.elements.logoutBtn = document.getElementById('btn-logout');
        this.elements.searchInput = document.getElementById('search-input');
        this.elements.searchBtn = document.getElementById('btn-search');
        
        // 密码列表相关
        this.elements.passwordsContainer = document.getElementById('passwords-container');
        this.elements.generatorContainer = document.getElementById('generator-container');
        this.elements.settingsContainer = document.getElementById('settings-container');
        this.elements.passwordsTable = document.getElementById('passwords-table');
        this.elements.addPasswordBtn = document.getElementById('btn-add-password');
        this.elements.categoryBtns = document.querySelectorAll('[data-category]');
        
        // 密码模态框相关
        this.elements.passwordModal = document.getElementById('password-modal');
        this.elements.passwordForm = document.getElementById('password-form');
        this.elements.passwordModalTitle = document.getElementById('password-modal-title');
        this.elements.passwordId = document.getElementById('password-id');
        this.elements.passwordName = document.getElementById('password-name');
        this.elements.passwordUsername = document.getElementById('password-username');
        this.elements.passwordValue = document.getElementById('password-value');
        this.elements.passwordUrl = document.getElementById('password-url');
        this.elements.passwordCategory = document.getElementById('password-category');
        this.elements.passwordNotes = document.getElementById('password-notes');
        this.elements.togglePasswordBtn = document.getElementById('btn-toggle-password');
        this.elements.useGeneratorBtn = document.getElementById('btn-use-generator');
        this.elements.savePasswordBtn = document.getElementById('btn-save-password');
        
        // 密码生成器相关
        this.elements.generatedPassword = document.getElementById('generated-password');
        this.elements.passwordLength = document.getElementById('password-length');
        this.elements.lengthValue = document.getElementById('length-value');
        this.elements.includeUppercase = document.getElementById('include-uppercase');
        this.elements.includeLowercase = document.getElementById('include-lowercase');
        this.elements.includeNumbers = document.getElementById('include-numbers');
        this.elements.includeSymbols = document.getElementById('include-symbols');
        this.elements.generatePasswordBtn = document.getElementById('btn-generate-password');
        this.elements.copyPasswordBtn = document.getElementById('btn-copy-password');
        
        // 设置相关
        this.elements.changeMasterPasswordForm = document.getElementById('change-master-password-form');
        this.elements.currentMasterPassword = document.getElementById('current-master-password');
        this.elements.newMasterPassword = document.getElementById('new-master-password');
        this.elements.confirmMasterPassword = document.getElementById('confirm-master-password');
        this.elements.exportDataBtn = document.getElementById('btn-export-data');
        this.elements.importDataBtn = document.getElementById('btn-import-data');
        this.elements.clearDataBtn = document.getElementById('btn-clear-data');

        // 安全设置相关
        this.elements.securitySettingsForm = document.getElementById('security-settings-form');
        this.elements.autoLogoutTime = document.getElementById('auto-logout-time');
        this.elements.passwordExpiryDays = document.getElementById('password-expiry-days');
    },

    /**
     * 绑定事件处理程序
     */
    bindEvents() {
        // 登录表单提交
        this.elements.loginForm.addEventListener('submit', this.handleLogin.bind(this));
        
        // 导航事件
        this.elements.navPasswords.addEventListener('click', this.showPasswordsList.bind(this));
        this.elements.navGenerator.addEventListener('click', this.showPasswordGenerator.bind(this));
        this.elements.navSettings.addEventListener('click', this.showSettings.bind(this));
        this.elements.logoutBtn.addEventListener('click', this.handleLogout.bind(this));
        
        // 搜索功能
        this.elements.searchInput.addEventListener('input', this.handleSearch.bind(this));
        this.elements.searchBtn.addEventListener('click', this.handleSearch.bind(this));
        
        // 类别过滤
        this.elements.categoryBtns.forEach(btn => {
            btn.addEventListener('click', this.handleCategoryFilter.bind(this));
        });
        
        // 添加密码按钮
        this.elements.addPasswordBtn.addEventListener('click', this.showAddPasswordModal.bind(this));
        
        // 密码表单相关
        this.elements.togglePasswordBtn.addEventListener('click', this.togglePasswordVisibility.bind(this));
        this.elements.useGeneratorBtn.addEventListener('click', this.useGeneratedPassword.bind(this));
        this.elements.savePasswordBtn.addEventListener('click', this.savePassword.bind(this));
        
        // 密码生成器相关
        this.elements.passwordLength.addEventListener('input', this.updateLengthValue.bind(this));
        this.elements.generatePasswordBtn.addEventListener('click', this.generatePassword.bind(this));
        this.elements.copyPasswordBtn.addEventListener('click', this.copyGeneratedPassword.bind(this));
        
        // 设置相关
        this.elements.changeMasterPasswordForm.addEventListener('submit', this.handleMasterPasswordChange.bind(this));
        this.elements.exportDataBtn.addEventListener('click', this.exportData.bind(this));
        this.elements.importDataBtn.addEventListener('click', this.importData.bind(this));
        this.elements.clearDataBtn.addEventListener('click', this.clearAllData.bind(this));
        
        // 安全设置表单提交
        this.elements.securitySettingsForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleSecuritySettingsSave();
        });
        
        // 用户活动监听（用于自动登出）
        document.addEventListener('click', this.resetAutoLogoutTimer.bind(this));
        document.addEventListener('keypress', this.resetAutoLogoutTimer.bind(this));
    },

    /**
     * 检查初始状态，显示对应界面
     */
    checkInitialState() {
        if (StorageModule.isMasterPasswordSet()) {
            // 已设置主密码，显示登录界面
            this.showLoginScreen();
        } else {
            // 未设置主密码，显示设置界面
            this.showSetupScreen();
        }
    },

    /**
     * 显示登录界面
     */
    showLoginScreen() {
        this.elements.masterPassword.placeholder = '请输入主密码';
        this.elements.loginForm.querySelector('button').textContent = '登录';
        this.elements.loginForm.querySelector('.form-text').textContent = '请输入您的主密码进行登录';
        this.elements.loginContainer.classList.remove('d-none');
        this.elements.appContainer.classList.add('d-none');
    },

    /**
     * 显示设置主密码界面
     */
    showSetupScreen() {
        this.elements.masterPassword.placeholder = '请设置主密码';
        this.elements.loginForm.querySelector('button').textContent = '创建密码库';
        this.elements.loginForm.querySelector('.form-text').textContent = '请设置一个强密码作为主密码，用于加密您的所有数据';
        this.elements.loginContainer.classList.remove('d-none');
        this.elements.appContainer.classList.add('d-none');
    },

    /**
     * 处理登录或设置主密码
     * @param {Event} e - 表单提交事件
     */
    handleLogin(e) {
        e.preventDefault();
        const masterPassword = this.elements.masterPassword.value.trim();
        
        if (!masterPassword) {
            this.showAlert('请输入主密码', 'danger');
            return;
        }
        
        if (StorageModule.isMasterPasswordSet()) {
            // 验证主密码
            if (StorageModule.verifyMasterPassword(masterPassword)) {
                // 初始化密码管理器
                if (PasswordManager.init(masterPassword)) {
                    this.showApp();
                    this.resetAutoLogoutTimer();
                } else {
                    this.showAlert('解密数据失败，请检查主密码', 'danger');
                }
            } else {
                this.showAlert('主密码错误，请重试', 'danger');
            }
        } else {
            // 设置主密码
            if (masterPassword.length < 8) {
                this.showAlert('主密码至少需要8个字符', 'danger');
                return;
            }
            
            // 检查密码强度
            const strength = CryptoModule.checkPasswordStrength(masterPassword);
            if (strength === 'weak') {
                this.showAlert('主密码强度太弱，请使用数字、大小写字母和特殊字符', 'warning');
                return;
            }
            
            // 设置主密码并初始化
            if (StorageModule.setupMasterPassword(masterPassword)) {
                if (PasswordManager.init(masterPassword)) {
                    this.showApp();
                    this.resetAutoLogoutTimer();
                    this.showAlert('密码库创建成功', 'success');
                } else {
                    this.showAlert('初始化密码管理器失败', 'danger');
                }
            } else {
                this.showAlert('设置主密码失败', 'danger');
            }
        }
        
        // 清空输入框
        this.elements.masterPassword.value = '';
    },

    /**
     * 显示主应用界面
     */
    showApp() {
        this.elements.loginContainer.classList.add('d-none');
        this.elements.appContainer.classList.remove('d-none');
        this.showPasswordsList();
        this.loadSecuritySettings();
        this.checkPasswordExpiry();
        this.resetAutoLogoutTimer();
    },

    /**
     * 显示密码列表
     * @param {Event} e - 点击事件（可选）
     */
    showPasswordsList(e) {
        if (e) e.preventDefault();
        
        // 更新导航活跃状态
        this.updateNavActiveState('passwords');
        
        // 显示密码列表容器，隐藏其他容器
        this.elements.passwordsContainer.classList.remove('d-none');
        this.elements.generatorContainer.classList.add('d-none');
        this.elements.settingsContainer.classList.add('d-none');
        
        // 渲染密码列表
        this.renderPasswordsList();
    },

    /**
     * 显示密码生成器
     * @param {Event} e - 点击事件
     */
    showPasswordGenerator(e) {
        e.preventDefault();
        
        // 更新导航活跃状态
        this.updateNavActiveState('generator');
        
        // 显示密码生成器容器，隐藏其他容器
        this.elements.passwordsContainer.classList.add('d-none');
        this.elements.generatorContainer.classList.remove('d-none');
        this.elements.settingsContainer.classList.add('d-none');
        
        // 生成一个新密码
        this.generatePassword();
    },

    /**
     * 显示设置界面
     * @param {Event} e - 点击事件
     */
    showSettings(e) {
        e.preventDefault();
        
        // 更新导航活跃状态
        this.updateNavActiveState('settings');
        
        // 显示设置容器，隐藏其他容器
        this.elements.passwordsContainer.classList.add('d-none');
        this.elements.generatorContainer.classList.add('d-none');
        this.elements.settingsContainer.classList.remove('d-none');
        
        // 清空设置表单
        this.elements.currentMasterPassword.value = '';
        this.elements.newMasterPassword.value = '';
        this.elements.confirmMasterPassword.value = '';
    },

    /**
     * 更新导航栏活跃状态
     * @param {string} active - 活跃的导航项（'passwords', 'generator', 'settings'）
     */
    updateNavActiveState(active) {
        this.elements.navPasswords.classList.toggle('active', active === 'passwords');
        this.elements.navGenerator.classList.toggle('active', active === 'generator');
        this.elements.navSettings.classList.toggle('active', active === 'settings');
    },

    /**
     * 渲染密码列表
     */
    renderPasswordsList() {
        const tbody = this.elements.passwordsTable.querySelector('tbody');
        const passwords = PasswordManager.getFilteredPasswords();
        
        // 清空表格
        tbody.innerHTML = '';
        
        if (passwords.length === 0) {
            // 没有密码，显示提示
            const tr = document.createElement('tr');
            tr.className = 'no-passwords-message';
            tr.innerHTML = `<td colspan="6" class="text-center">暂无密码记录，请点击"添加密码"按钮创建</td>`;
            tbody.appendChild(tr);
            return;
        }
        
        // 添加密码行
        passwords.forEach(password => {
            const tr = document.createElement('tr');
            
            // 检查密码是否过期
            const expiryStatus = PasswordManager.getPasswordExpiryStatus(password);
            if (expiryStatus.expired) {
                tr.classList.add('table-danger');
            } else if (expiryStatus.daysLeft <= 7) {
                tr.classList.add('table-warning');
            }
            
            tr.innerHTML = `
                <td>
                    ${password.url ? `<a href="${password.url}" target="_blank" rel="noopener">` : ''}
                    ${this.escapeHtml(password.name)}
                    ${password.url ? `</a>` : ''}
                </td>
                <td>${this.escapeHtml(password.username)}</td>
                <td>
                    <div class="d-flex align-items-center">
                        <span class="password-dots">••••••••</span>
                        <button class="btn btn-sm btn-outline-secondary ms-2 btn-show-password" data-id="${password.id}">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-secondary ms-1 btn-copy-password" data-id="${password.id}">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                </td>
                <td>
                    <span class="badge category-badge category-${password.category}">
                        ${this.getCategoryName(password.category)}
                    </span>
                </td>
                <td>${this.formatDate(password.lastModified)}</td>
                <td class="action-buttons">
                    <button class="btn btn-primary btn-edit-password" data-id="${password.id}">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-danger btn-delete-password" data-id="${password.id}">
                        <i class="fas fa-trash-alt"></i>
                    </button>
                </td>
            `;
            
            tbody.appendChild(tr);
            
            // 绑定按钮事件
            const showBtn = tr.querySelector('.btn-show-password');
            const copyBtn = tr.querySelector('.btn-copy-password');
            const editBtn = tr.querySelector('.btn-edit-password');
            const deleteBtn = tr.querySelector('.btn-delete-password');
            
            showBtn.addEventListener('click', () => this.togglePasswordDisplay(password.id));
            copyBtn.addEventListener('click', () => this.copyPassword(password.id));
            editBtn.addEventListener('click', () => this.showEditPasswordModal(password.id));
            deleteBtn.addEventListener('click', () => this.confirmDeletePassword(password.id));
        });
    },

    /**
     * 显示添加密码模态框
     */
    showAddPasswordModal() {
        // 重置表单
        this.elements.passwordForm.reset();
        this.elements.passwordId.value = '';
        this.elements.passwordModalTitle.textContent = '添加密码';
        this.currentEditingId = null;
        
        // 显示模态框
        const modal = new bootstrap.Modal(this.elements.passwordModal);
        modal.show();
        
        // 在模态框显示后设置焦点到第一个输入框
        this.elements.passwordModal.addEventListener('shown.bs.modal', () => {
            this.elements.passwordName.focus();
        }, { once: true });
    },

    /**
     * 显示编辑密码模态框
     * @param {number} id - 密码ID
     */
    showEditPasswordModal(id) {
        const password = PasswordManager.getPassword(id);
        if (!password) return;
        
        // 填充表单
        this.elements.passwordId.value = password.id;
        this.elements.passwordName.value = password.name;
        this.elements.passwordUsername.value = password.username;
        this.elements.passwordValue.value = password.password;
        this.elements.passwordUrl.value = password.url || '';
        this.elements.passwordCategory.value = password.category;
        this.elements.passwordNotes.value = password.notes || '';
        
        // 更新模态框标题
        this.elements.passwordModalTitle.textContent = '编辑密码';
        this.currentEditingId = id;
        
        // 显示模态框
        const modal = new bootstrap.Modal(this.elements.passwordModal);
        modal.show();
        
        // 在模态框显示后设置焦点到第一个输入框
        this.elements.passwordModal.addEventListener('shown.bs.modal', () => {
            this.elements.passwordName.focus();
        }, { once: true });
    },

    /**
     * 清除遮罩层
     * 解决modal关闭后遮罩层没有移除的问题
     */
    clearBackdrop() {
        // 移除所有modal-backdrop元素
        const backdrops = document.querySelectorAll('.modal-backdrop');
        backdrops.forEach(backdrop => {
            backdrop.remove();
        });
        // 移除body上的modal-open类
        document.body.classList.remove('modal-open');
        document.body.style.overflow = '';
        document.body.style.paddingRight = '';
        
        // 移除aria-hidden属性
        this.elements.passwordModal.removeAttribute('aria-hidden');
        
        // 将焦点返回到触发模态框的元素
        const triggerElement = document.activeElement;
        if (triggerElement && triggerElement !== document.body) {
            triggerElement.focus();
        }
    },

    /**
     * 保存密码（添加或编辑）
     */
    savePassword() {
        // 获取表单数据
        const id = this.elements.passwordId.value;
        const name = this.elements.passwordName.value.trim();
        const username = this.elements.passwordUsername.value.trim();
        const password = this.elements.passwordValue.value;
        const url = this.elements.passwordUrl.value.trim();
        const category = this.elements.passwordCategory.value;
        const notes = this.elements.passwordNotes.value.trim();
        
        // 验证必填字段
        if (!name || !username || !password) {
            this.showAlert('名称、用户名和密码为必填项', 'danger', this.elements.passwordModal);
            return;
        }
        
        // 验证URL格式（如果有）
        if (url && !this.isValidUrl(url)) {
            this.showAlert('请输入有效的URL地址', 'danger', this.elements.passwordModal);
            return;
        }
        
        // 准备数据
        const passwordData = {
            name,
            username,
            password,
            url,
            category,
            notes,
            lastModified: new Date().toISOString()
        };
        
        let success = false;
        let message = '';
        
        if (id) {
            // 编辑现有密码
            success = PasswordManager.updatePassword(id, passwordData);
            message = success ? '密码更新成功' : '密码更新失败';
        } else {
            // 添加新密码
            success = PasswordManager.addPassword(passwordData);
            message = success ? '密码添加成功' : '密码添加失败';
        }
        
        if (success) {
            // 关闭模态框
            const modalInstance = bootstrap.Modal.getInstance(this.elements.passwordModal);
            modalInstance.hide();
            
            // 清理遮罩层
            this.clearBackdrop();
            
            // 重新渲染密码列表
            this.renderPasswordsList();
            this.showAlert(message, 'success');
            
            // 将焦点返回到添加密码按钮
            this.elements.addPasswordBtn.focus();
        } else {
            this.showAlert(message, 'danger', this.elements.passwordModal);
        }
    },

    /**
     * 确认删除密码
     * @param {string} id - 密码ID
     */
    confirmDeletePassword(id) {
        if (confirm('确定要删除这个密码吗？此操作不可恢复。')) {
            if (PasswordManager.deletePassword(id)) {
                this.renderPasswordsList();
                this.showAlert('密码已删除', 'success');
            } else {
                this.showAlert('删除密码失败', 'danger');
            }
        }
        
        // 确保清除任何可能存在的遮罩层
        this.clearBackdrop();
    },

    /**
     * 切换密码显示/隐藏
     * @param {number} id - 密码ID
     */
    togglePasswordDisplay(id) {
        const password = PasswordManager.getPassword(id);
        if (!password) return;
        
        const tr = this.elements.passwordsTable.querySelector(`button[data-id="${id}"].btn-show-password`).closest('tr');
        const passwordCell = tr.querySelector('.password-dots');
        const showBtn = tr.querySelector('.btn-show-password i');
        
        if (passwordCell.classList.contains('password-field')) {
            // 隐藏密码
            passwordCell.textContent = '••••••••';
            passwordCell.classList.remove('password-field');
            showBtn.classList.remove('fa-eye-slash');
            showBtn.classList.add('fa-eye');
        } else {
            // 显示密码
            passwordCell.textContent = password.password;
            passwordCell.classList.add('password-field');
            showBtn.classList.remove('fa-eye');
            showBtn.classList.add('fa-eye-slash');
            
            // 自动隐藏密码（10秒后）
            setTimeout(() => {
                if (passwordCell) {
                    passwordCell.textContent = '••••••••';
                    passwordCell.classList.remove('password-field');
                    showBtn.classList.remove('fa-eye-slash');
                    showBtn.classList.add('fa-eye');
                }
            }, 10000);
        }
    },

    /**
     * 复制密码到剪贴板
     * @param {number} id - 密码ID
     */
    copyPassword(id) {
        const password = PasswordManager.getPassword(id);
        if (!password) return;
        
        navigator.clipboard.writeText(password.password)
            .then(() => {
                const btn = this.elements.passwordsTable.querySelector(`button[data-id="${id}"].btn-copy-password`);
                this.showTooltip(btn, '已复制');
            })
            .catch(err => {
                console.error('复制失败:', err);
                this.showAlert('复制密码失败', 'danger');
            });
    },

    /**
     * 处理密码类别过滤
     * @param {Event} e - 点击事件
     */
    handleCategoryFilter(e) {
        const category = e.target.dataset.category;
        if (!category) return;
        
        // 更新活跃状态
        this.elements.categoryBtns.forEach(btn => {
            btn.classList.toggle('active', btn.dataset.category === category);
        });
        
        // 设置当前类别并重新渲染
        PasswordManager.setCategory(category);
        this.renderPasswordsList();
    },

    /**
     * 处理搜索
     */
    handleSearch() {
        const keyword = this.elements.searchInput.value.trim();
        PasswordManager.setSearchKeyword(keyword);
        this.renderPasswordsList();
    },

    /**
     * 生成随机密码
     */
    generatePassword() {
        const options = {
            length: parseInt(this.elements.passwordLength.value),
            uppercase: this.elements.includeUppercase.checked,
            lowercase: this.elements.includeLowercase.checked,
            numbers: this.elements.includeNumbers.checked,
            symbols: this.elements.includeSymbols.checked
        };
        
        const password = PasswordManager.generatePassword(options);
        this.elements.generatedPassword.value = password;
        
        // 显示密码强度
        const strength = PasswordManager.analyzePasswordStrength(password);
        this.updatePasswordStrengthIndicator(strength, this.elements.generatedPassword.parentElement);
    },

    /**
     * 复制生成的密码
     */
    copyGeneratedPassword() {
        const password = this.elements.generatedPassword.value;
        if (!password) return;
        
        navigator.clipboard.writeText(password)
            .catch(err => {
                console.error('复制失败:', err);
                this.showAlert('复制密码失败', 'danger');
            });
    },

    /**
     * 使用生成的密码填充表单
     */
    useGeneratedPassword() {
        // 生成一个新密码
        const options = {
            length: 16, // 默认使用更长的密码
            uppercase: true,
            lowercase: true,
            numbers: true,
            symbols: true
        };
        
        const password = PasswordManager.generatePassword(options);
        this.elements.passwordValue.value = password;
        
        // 手动触发input事件以更新密码强度指示器
        const event = new Event('input', {
            bubbles: true,
            cancelable: true
        });
        this.elements.passwordValue.dispatchEvent(event);
    },

    /**
     * 更新密码长度显示
     */
    updateLengthValue() {
        const length = this.elements.passwordLength.value;
        this.elements.lengthValue.textContent = length;
    },

    /**
     * 切换密码可见性
     */
    togglePasswordVisibility() {
        const input = this.elements.passwordValue;
        const icon = this.elements.togglePasswordBtn.querySelector('i');
        
        if (input.type === 'password') {
            input.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        } else {
            input.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }
    },

    /**
     * 处理主密码修改
     * @param {Event} e - 表单提交事件
     */
    handleMasterPasswordChange(e) {
        e.preventDefault();
        
        const currentPassword = this.elements.currentMasterPassword.value;
        const newPassword = this.elements.newMasterPassword.value;
        const confirmPassword = this.elements.confirmMasterPassword.value;
        
        // 验证新密码
        if (newPassword !== confirmPassword) {
            this.showAlert('新密码和确认密码不匹配', 'danger');
            return;
        }
        
        // 验证新密码强度
        const strength = CryptoModule.checkPasswordStrength(newPassword);
        if (strength === 'weak') {
            this.showAlert('新密码强度太弱，请使用更强的密码', 'warning');
            return;
        }
        
        try {
            // 显示加载提示
            const submitButton = e.target.querySelector('button[type="submit"]');
            const originalText = submitButton.innerHTML;
            submitButton.disabled = true;
            submitButton.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>正在处理...';
            
            // 更改主密码
            StorageModule.changeMasterPassword(currentPassword, newPassword);
            
            // 更新当前主密码
            PasswordManager.currentMasterPassword = newPassword;
            
            // 重置表单
            e.target.reset();
            
            // 恢复按钮状态
            submitButton.disabled = false;
            submitButton.innerHTML = originalText;
            
            // 显示成功消息
            this.showAlert('主密码修改成功，请使用新密码重新登录', 'success');
            
            // 延迟1秒后退出登录，让用户看到成功消息
            setTimeout(() => {
                this.handleLogout();
            }, 1000);
        } catch (error) {
            // 恢复按钮状态
            const submitButton = e.target.querySelector('button[type="submit"]');
            submitButton.disabled = false;
            submitButton.innerHTML = originalText;
            
            // 显示错误消息
            this.showAlert(error.message || '主密码修改失败', 'danger');
        }
    },

    /**
     * 导出数据
     */
    exportData() {
        const exportUrl = StorageModule.exportData();
        
        // 创建下载链接
        const a = document.createElement('a');
        a.href = exportUrl;
        a.download = `password-manager-backup-${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        
        // 释放URL对象
        window.URL.revokeObjectURL(exportUrl);
        
        this.showAlert('数据导出成功', 'success');
    },

    /**
     * 导入数据
     */
    importData() {
        // 创建文件输入元素
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.json';
        
        input.onchange = e => {
            const file = e.target.files[0];
            if (!file) return;
            
            const reader = new FileReader();
            reader.onload = event => {
                try {
                    const jsonData = event.target.result;
                    
                    // 确认主密码
                    const masterPassword = prompt('请输入您的主密码以验证导入的数据');
                    if (!masterPassword) return;
                    
                    if (StorageModule.importData(jsonData, masterPassword)) {
                        // 重新初始化密码管理器
                        if (PasswordManager.init(masterPassword)) {
                            this.renderPasswordsList();
                            this.showAlert('数据导入成功', 'success');
                        } else {
                            this.showAlert('初始化密码管理器失败', 'danger');
                        }
                    } else {
                        this.showAlert('导入数据失败，请检查文件格式和主密码', 'danger');
                    }
                } catch (e) {
                    console.error('导入数据失败:', e);
                    this.showAlert('导入数据失败，文件格式错误', 'danger');
                }
            };
            reader.readAsText(file);
        };
        
        input.click();
    },

    /**
     * 清除所有数据
     */
    clearAllData() {
        if (confirm('您确定要清除所有数据吗？此操作不可撤销！')) {
            if (confirm('最后确认：所有密码数据将被永久删除。是否继续？')) {
                if (StorageModule.clearAllData()) {
                    this.handleLogout();
                    this.showAlert('所有数据已清除', 'success');
                } else {
                    this.showAlert('清除数据失败', 'danger');
                }
            }
        }
    },

    /**
     * 处理登出
     */
    handleLogout() {
        PasswordManager.logout();
        // 清除自动登出计时器
        clearTimeout(this.autoLogoutTimer);
        this.showLoginScreen();
        
        // 清除可能存在的模态框遮罩
        this.clearBackdrop();
    },

    /**
     * 重置自动登出计时器
     */
    resetAutoLogoutTimer() {
        clearTimeout(this.autoLogoutTimer);
        
        // 如果未登录，不设置计时器
        if (this.elements.appContainer.classList.contains('d-none')) {
            return;
        }
        
        // 获取自动登出时间设置
        const settings = StorageModule.getSecuritySettings();
        if (settings.autoLogout === 0) return; // 如果禁用自动登出，则不设置计时器
        
        // 设置新的计时器
        this.autoLogoutTimer = setTimeout(() => {
            // 如果已登录，则自动登出
            if (!this.elements.appContainer.classList.contains('d-none')) {
                this.handleLogout();
                this.showAlert('由于长时间无操作，系统已自动登出', 'info');
            }
        }, settings.autoLogout * 60 * 1000);
    },

    /**
     * 显示提示信息
     * @param {string} message - 提示消息
     * @param {string} type - 提示类型（success, info, warning, danger）
     * @param {Element|string} target - 目标容器元素或ID（可选）
     */
    showAlert(message, type, target = null) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
        alertDiv.role = 'alert';
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        `;
        
        // 添加到目标容器
        let container;
        if (target) {
            // 如果target是DOM元素，直接使用
            if (target instanceof Element) {
                container = target;
            } else {
                // 如果target是字符串，则作为ID查找
                container = document.querySelector(`#${target} .modal-body`);
                if (!container) container = document.querySelector(`#${target}`);
            }
        } else {
            container = document.querySelector('.container:not(.d-none)');
            if (!container) container = document.body;
        }
        
        // 插入到容器顶部
        container.insertBefore(alertDiv, container.firstChild);
        
        // 自动关闭
        setTimeout(() => {
            alertDiv.classList.remove('show');
            setTimeout(() => alertDiv.remove(), 150);
        }, 3000);
    },

    /**
     * 显示工具提示
     * @param {Element} element - 目标元素
     * @param {string} text - 提示文本
     */
    showTooltip(element, text) {
        const tooltip = document.createElement('div');
        tooltip.className = 'copy-tooltip';
        tooltip.textContent = text;
        
        // 计算位置
        const rect = element.getBoundingClientRect();
        tooltip.style.left = `${rect.left + rect.width / 2 - 30}px`;
        tooltip.style.top = `${rect.top - 30}px`;
        
        document.body.appendChild(tooltip);
        
        // 自动移除
        setTimeout(() => tooltip.remove(), 1500);
    },

    /**
     * 更新密码强度指示器
     * @param {string} strength - 密码强度（weak, medium, strong, very-strong）
     * @param {Element} container - 容器元素
     */
    updatePasswordStrengthIndicator(strength, container) {
        if (!container) return; // 添加容器检查
        
        // 移除现有的强度指示器
        const existingIndicator = container.querySelector('.password-strength');
        if (existingIndicator) {
            existingIndicator.remove();
        }
        
        // 创建新的强度指示器
        const indicator = document.createElement('div');
        indicator.className = 'password-strength';
        
        // 创建强度条
        const strengthBar = document.createElement('div');
        strengthBar.className = 'strength-bar';
        
        // 根据强度设置不同的样式
        let strengthText = '';
        let strengthClass = '';
        let strengthWidth = '0%';
        
        switch (strength) {
            case 'weak':
                strengthText = '弱';
                strengthClass = 'weak';
                strengthWidth = '25%';
                break;
            case 'medium':
                strengthText = '中';
                strengthClass = 'medium';
                strengthWidth = '50%';
                break;
            case 'strong':
                strengthText = '强';
                strengthClass = 'strong';
                strengthWidth = '75%';
                break;
            case 'very-strong':
                strengthText = '很强';
                strengthClass = 'very-strong';
                strengthWidth = '100%';
                break;
        }
        
        // 设置强度条的样式
        strengthBar.style.width = strengthWidth;
        strengthBar.classList.add(strengthClass);
        
        // 创建强度文本
        const strengthTextElement = document.createElement('span');
        strengthTextElement.className = 'strength-text';
        strengthTextElement.textContent = strengthText;
        
        // 组装强度指示器
        indicator.appendChild(strengthBar);
        indicator.appendChild(strengthTextElement);
        
        // 添加到容器
        container.appendChild(indicator);
    },

    /**
     * 获取类别显示名称
     * @param {string} category - 类别代码
     * @returns {string} - 类别显示名称
     */
    getCategoryName(category) {
        const names = {
            'website': '网站',
            'app': '应用',
            'other': '其他'
        };
        return names[category] || category;
    },

    /**
     * 格式化日期
     * @param {string} dateString - ISO日期字符串
     * @returns {string} - 格式化后的日期字符串
     */
    formatDate(dateString) {
        if (!dateString) return '未知';
        
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    },

    /**
     * 验证URL格式
     * @param {string} url - URL字符串
     * @returns {boolean} - 是否为有效URL
     */
    isValidUrl(url) {
        try {
            new URL(url);
            return true;
        } catch (e) {
            return false;
        }
    },

    /**
     * 转义HTML字符
     * @param {string} text - 输入文本
     * @returns {string} - 转义后的文本
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    },

    /**
     * 初始化UI事件监听
     */
    initEventListeners() {
        // 添加密码强度实时检测
        this.elements.masterPassword.addEventListener('input', () => {
            const container = this.elements.masterPassword.parentElement.querySelector('.password-strength-container');
            if (container) {
                const strength = CryptoModule.checkPasswordStrength(this.elements.masterPassword.value);
                this.updatePasswordStrengthIndicator(strength, container);
            }
        });

        this.elements.newMasterPassword.addEventListener('input', () => {
            const container = this.elements.newMasterPassword.parentElement.querySelector('.password-strength-container');
            if (container) {
                const strength = CryptoModule.checkPasswordStrength(this.elements.newMasterPassword.value);
                this.updatePasswordStrengthIndicator(strength, container);
            }
        });

        this.elements.passwordValue.addEventListener('input', () => {
            const container = this.elements.passwordValue.parentElement.parentElement.querySelector('.password-strength-container');
            if (container) {
                const strength = CryptoModule.checkPasswordStrength(this.elements.passwordValue.value);
                this.updatePasswordStrengthIndicator(strength, container);
            }
        });

        // 安全设置表单提交
        this.elements.securitySettingsForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleSecuritySettingsSave();
        });
    },

    /**
     * 处理安全设置保存
     */
    handleSecuritySettingsSave() {
        const settings = {
            autoLogout: parseInt(this.elements.autoLogoutTime.value),
            passwordExpiry: parseInt(this.elements.passwordExpiryDays.value)
        };

        if (StorageModule.saveSecuritySettings(settings)) {
            this.showAlert('安全设置已保存', 'success');
            // 重置自动登出计时器
            this.resetAutoLogoutTimer();
        } else {
            this.showAlert('保存安全设置失败', 'danger');
        }
    },

    /**
     * 加载安全设置
     */
    loadSecuritySettings() {
        const settings = StorageModule.getSecuritySettings();
        this.elements.autoLogoutTime.value = settings.autoLogout;
        this.elements.passwordExpiryDays.value = settings.passwordExpiry;
    },

    /**
     * 检查密码过期状态
     */
    checkPasswordExpiry() {
        try {
            const passwords = StorageModule.getPasswords(PasswordManager.currentMasterPassword);
            if (!passwords || passwords.length === 0) return;
            
            const expiredPasswords = passwords.filter(p => StorageModule.isPasswordExpired(p.id));
            
            if (expiredPasswords.length > 0) {
                const message = `有 ${expiredPasswords.length} 个密码已过期，请及时更新。`;
                this.showAlert(message, 'warning');
            }
        } catch (error) {
            console.error('检查密码过期状态失败:', error);
        }
    },

    /**
     * 显示主应用界面
     */
    showAppScreen() {
        this.elements.loginContainer.classList.add('d-none');
        this.elements.appContainer.classList.remove('d-none');
        this.loadPasswords();
        this.loadSecuritySettings();
        this.checkPasswordExpiry();
        this.resetAutoLogoutTimer();
    }
}; 